import sys
import os
from PySide6.QtWidgets import QApplication,QStyle
from PySide6 import QtCore
from ConsWindow import ConsWindow
from MyLogger import MyLogger
from MyConfig import MyConfig
from VersionChecker import VersionChecker
import yaml

if __name__=="__main__":
    
    cur_path = os.path.dirname(os.path.realpath(__file__))+"\\"
    try:
       cur_path = sys._MEIPASS+"\\"
    except : pass
    settings = MyConfig(cur_path+"config.json")
    logFile = settings.get("LogFile",defaultValue="default.log")
    if os.path.isfile(logFile): os.remove(logFile)
    logger=MyLogger(__name__,log_file=logFile,outStream=sys.stdout)    
    try:
        if not os.path.isfile(cur_path+"metadata.yml"): raise Exception("Отсутствует файл metadata.yml")
        metadata:dict = {}
        with open(cur_path+"metadata.yml",mode="r",encoding="UTF-8") as f: metadata = yaml.load(f, Loader=yaml.FullLoader)
        vc = VersionChecker(metadata)
        update_exists = vc.update_exists()
        logger.info(f"start application version({vc.current_version})")
        logger.info(f"update exists: {update_exists}. Update version {vc.update_version}. [{vc.distr_url}]")
        need_update=False
        if update_exists: 
            need_update = vc.show_update_dialog()
            logger.info(f"need update: {need_update}")
        os.environ["PYSIDE_DESIGNER_PLUGINS"]="."
        os.environ["QTWEBENGINE_DISABLE_SANDBOX"]="1"
        QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)
        app = QApplication(sys.argv) if not QApplication.instance() else QApplication.instance()
        style = settings.get("AppStyle",defaultValue="Windows")
        app.setStyle(style)
        window = ConsWindow(metadata,need_update,vc.distr_url)
        window.MainWindow.show()
        res=app.exec()
        # print(res)
        sys.exit(res)
    except Exception as exp:
        logger.error(f"general error",exc_info=True)